package com.jzy.controller.admin;

import com.jzy.constant.WebConstant;
import com.jzy.controller.BaseController;
import com.jzy.dto.Types;
import com.jzy.entity.Bo.RestResponseBo;
import com.jzy.entity.Vo.ContentVo;
import com.jzy.entity.Vo.UserVo;
import com.jzy.exception.TipException;
import com.jzy.service.IContentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("admin/page")
public class PageController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PageController.class);

    @Resource
    private IContentService contentsService;

    @GetMapping(value = "")
    public String index(Model model) {
        Page<ContentVo> articlesWithPage = contentsService.getArticlesWithPage(1, WebConstant.MAX_POSTS, Types.PAGE.getType());
        model.addAttribute("articles", articlesWithPage.getContent());
        return "admin/page_list";
    }

    @GetMapping(value = "new")
    public String newPage() {
        return "admin/page_edit";
    }

    @PostMapping(value = "publish")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponseBo publishPage(ContentVo content, HttpServletRequest request) {
        UserVo users = this.user(request);
        content.setType(Types.PAGE.getType());
        content.setAuthorId(users.getUid());
        try {
            contentsService.publish(content);
        } catch (Exception e) {
            String msg = "页面发布失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }
}
